<script lang="ts" setup>
import { ref, reactive, onMounted, } from 'vue'
import axios from "axios";
import { taskListApiUrl,taskCategoryUrl,taskAddApiUrl,taskUpdateApiUrl } from '@/api.config.js';
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage,  } from 'element-plus'

const tableData = ref([])
const loading = ref(false)
const initSift = () => ({
  status: null,
  update_time: null,
  category: null,
})
const categoryOptions = ref(null)
const sift = reactive(initSift())
const initPagination = () => ({
  page: 1,
  pageSize: 10,
  total: 0
})
const pagination = reactive(initPagination())
const drawerVisible = ref(false)
const refresh = () => {
  Object.assign(sift, initSift())
  Object.assign(pagination, initPagination())
  Object.assign(task, initTask())
  getList()
}

const getList = (cb=null) => {
  const data = {
    page: pagination.page,
    size: pagination.pageSize,
    completed: sift.status,
    category: sift.category,
    update_time: sift.update_time ? Math.floor(sift.update_time.getTime() / 1000) : null,
  }
  loading.value = true
  axios.post(
      taskListApiUrl,
      data,
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
  ).then(res => {
    tableData.value = res.data.data.list
    pagination.total = Number(res.data.data.total)
  }).finally(() => {
    loading.value = false
    cb && cb()
  })
}

const initTask = () => ({
  id: null,
  content: '',
  task: '',
  urgent: null,
  category: null,
  del: null,
  status: null,
})
const task = reactive(initTask())

const logList = ref([])
const cpLog = () => {
  const divElement = document.getElementById("copy_path");
  if (!divElement || !window.getSelection) return;
  const selection = window.getSelection();
  if (!selection) return;
  const range = document.createRange();
  range.selectNodeContents(divElement);
  selection.removeAllRanges();
  selection.addRange(range);
  document.execCommand("copy");
  // 取消选中区域
  selection.empty();
  ElMessage('已复制')
}
const getDailyLog = (cb=null) => {
  cardLoading.value = true
  sift.update_time = sift.update_time ?? new Date()
  const data = {
    page: 1,
    size: 99999,
    completed: 1,
    update_time: sift.update_time ? Math.floor(sift.update_time.getTime() / 1000) : null,
  }
  axios.post(
      taskListApiUrl,
      data,
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
  ).then(res => {
    logList.value = res.data.data.list
  }).finally(() => {
    cb&&cb()
    cardLoading.value = false
  })
}
const handleCloseDrawer = () => {
  Object.assign(task, initTask())
}
const edit = () => {
  let url = taskAddApiUrl
  if(task.id) {
    url = taskUpdateApiUrl
  }
  task.urgent = Number(task.urgent)
  if(task.content){
    task.task = task.content
  }
  axios.post(url, task, {headers: { 'Content-Type': 'application/x-www-form-urlencoded' }})
      .then(res => {
        if(res.data.code === 0){
          ElMessage('操作成功')
          drawerVisible.value = false
          refresh()
        }
      })
}
const deleteTask = id => {
  task.id = id
  task.del = 1
  edit()
}
const restoreTask = (id:number, status:number) => {
  task.id = id
  task.status = status
  edit()
}
const handleClick = (type:string, data=null, cb=null) => {
  cb&&cb()
  switch (type){
    case 'add':
      drawerVisible.value = true
      break
    case 'complete':
      restoreTask(data.id, 1)
      break
    case 'edit':
      drawerVisible.value = true
      Object.assign(task, data)
      break
    case 'delete':
      deleteTask(data.id)
      break
    case 'restore':
      restoreTask(data.id, 0)
      break
    case 'search':
      getList()
        getDailyLog()
      break
    case 'refresh':
      refresh()
        getDailyLog()
      break
    case 'log':
      if(!showDash.value){
        showDash.value = true
        getDailyLog()
      }else{
        showDash.value = false
      }
      break
    default:
  }
}

const handlePageChange = (e) => {
  pagination.page = e
  getList()
}

const  getCategories = () => {
  axios.post(
      taskCategoryUrl,
      {},
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
  .then(res => {
    categoryOptions.value = res.data.data
  })
}

onMounted(() => {
  getCategories()
  getList()
  // getDailyLog()
})
const showDash = ref(false)
const cardLoading = ref(false)
</script>

<template>
  <div style="padding: 0 32px 60px;">
    <div class="shLine" v-if="showDash">
      <el-space>
        <el-card style="min-width: 480px;min-height: 200px;" v-loading="cardLoading">
          <template #header>
            <div class="card-header">
              <span>Daily Log</span>
              <el-link @click="cpLog">Copy</el-link>
            </div>
          </template>
          <div id="copy_path" v-if="logList">
            <div v-for="(log, logIdx) in logList" :key="log.id" class="text item">{{logIdx+1}}.&nbsp;{{log.content}}</div>
          </div>
          <div v-else>
            <el-empty>暂无记录</el-empty>
          </div>
        </el-card>
      </el-space>
    </div>

    <el-divider></el-divider>

    <el-row :gutter="20" style="padding: 0 0 30px;">
      <el-col :span="4">
        <el-select v-model="sift.status" clearable placeholder="选择状态">
          <el-option label="已完成" value="1"></el-option>
          <el-option label="未完成" value="0"></el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select v-model="sift.category" clearable placeholder="选择类型">
          <el-option :label="item.name" :value="item.id" v-for="item in categoryOptions"></el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-date-picker
            v-model="sift.update_time"
            type="date"
            placeholder="选择日期"
        />
      </el-col>
      <el-col :span="12">
          <el-space>
            <el-button type="primary" @click="handleClick('search')">Search</el-button>
            <el-button type="info" @click="handleClick('refresh')">Refresh</el-button>
            <el-button type="success" @click="handleClick('add')">Add</el-button>
            <el-button type="" @click="handleClick('log')">Dashboard</el-button>
          </el-space>
      </el-col>
    </el-row>

    <el-table
        ref="multipleTableRef"
        row-key="id"
        v-loading="loading"
        style="width: 100%"
        border
        :data="tableData"
    >
      <el-table-column property="id" label="ID" width="60"></el-table-column>
      <el-table-column property="content" label="Task" min-width="120px">
        <template #default="scope">
          <el-link :style="{
          'text-decoration': scope.row.status == 1 ? 'line-through' : 'none',
          'color': scope.row.status==1?'#999':'#666'
        }">
            {{scope.row.content}}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column property="category" label="Category" width="120px">
        <template #default="scope">
          <el-tag type="info">{{scope.row.category_n}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column property="urgent" label="Ember" width="120px">
        <template #default="scope">
          <el-tag :type="scope.row.urgent==1?'danger':'primary'">{{scope.row.urgent == 1 ? '紧急' : '非紧急'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column property="status" label="Status" width="120px">
        <template #default="scope"><span style="color:#666;font-size: 12px;">{{scope.row.status==1?'已完成':'未完成'}}</span></template>
      </el-table-column>
      <el-table-column property="create_time" label="Create" width="220px" />
      <el-table-column fixed="right" label="Operations" width="220px">
        <template #default="scope">
          <el-space>
            <el-popconfirm
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="确定完成?"
                v-if="scope.row.status == 0"
            >
              <template #reference>
                <el-button type="success" size="small">完成</el-button>
              </template>
              <template #actions="{ confirm, cancel }">
                <el-button size="small" @click="cancel">取消</el-button>
                <el-button
                    type="danger"
                    size="small"
                    @click="handleClick('complete', scope.row, confirm)"
                >
                  确认
                </el-button>
              </template>
            </el-popconfirm>
            <el-button type="primary" size="small" @click="handleClick('edit', scope.row)" v-if="scope.row.status == 0">编辑</el-button>
            <el-popconfirm
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="确定重置?"
                v-if="scope.row.status == 1"
            >
              <template #reference>
                <el-button type="success" size="small">重置</el-button>
              </template>
              <template #actions="{ confirm, cancel }">
                <el-button size="small" @click="cancel">取消</el-button>
                <el-button
                    type="danger"
                    size="small"
                    @click="handleClick('restore', scope.row, confirm)"
                >
                  确认
                </el-button>
              </template>
            </el-popconfirm>
<!--            <el-button type="success" size="small" v-if="scope.row.status==1">重置</el-button>-->
            <el-popconfirm
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="确定删除?"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
              <template #actions="{ confirm, cancel }">
                <el-button size="small" @click="cancel">取消</el-button>
                <el-button
                    type="danger"
                    size="small"
                    @click="handleClick('delete', scope.row, confirm)"
                >
                  确认
                </el-button>
              </template>
            </el-popconfirm>
          </el-space>
        </template>
      </el-table-column>
      <template #empty>
        <div class="middle"><el-empty description="No Data" /></div>
      </template>
    </el-table>
    <div class="page">
      <el-pagination background layout="prev, pager, next" :total="pagination.total" @currentChange="handlePageChange" />
    </div>

    <el-drawer
        v-model="drawerVisible"
        title="记录"
        direction="rtl"
        size="40%"
        @close="handleCloseDrawer"
    >
        <div style="width: 80%;">
          <el-input
              type="textarea"
              style="margin-bottom: 20px;"
              :rows="4"
              placeholder="请输入任务描述" v-model="task.content"></el-input>

          <el-select size="default" style="margin-bottom: 20px;" v-model="task.category" placeholder="请选择类型">
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>

          <el-checkbox style="display:block;margin-bottom: 20px;" v-model="task.urgent">{{task.urgent?'加急':'不急'}}</el-checkbox>

          <el-button type="primary" @click="edit">提交</el-button>
        </div>
    </el-drawer>

  </div>
</template>

<style scoped>
.middle{
  display: flex;
  justify-content: center;
  align-items: center;
}
.page{
  padding: 32px 0;
  display: flex;
  justify-content: flex-end;
}
.card-header{
  display: flex;
  justify-content: space-between;
}
</style>